<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>阿新脚本-更新xhr</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <style>
      body,div{margin: 0; padding: 0;}
      .rxui {display: flex; justify-content: center; align-items: center; font-size: 12px;}

      .rxui_content {padding: 10px; overflow: hidden;}

      .rxui_title {font-weight: bold;}

      .rxui_input {margin: 20px 0;}
      .rxui_input_content {display: flex; flex-direction: row; align-items: center; margin-bottom: 15px;}
      .rxui_input_content:last-child {margin-bottom: 0;}
      .rxui_input .ric_des {margin-right: 5px;}
      .rxui_input .div_input {flex: 1; margin-right: 5px; min-width: 20px;}

      .rxui_buttons {display: flex; justify-content: center; align-items: center; }
      .rxui_button {margin-right: 30px; padding: 5px 10px;}
      .rxui_button:last-child { margin-right: 0;}

      .des {margin-top: 30px; background-color: azure;}
      .des span {font-size: 10px;}
    </style>
<body onload="getCacheConfigFn()">
  <div class="rxui">
    <div class="rxui_content">
      <div class="rxui_title">欢迎使用 <阿新更新> [源码]</div>
      <div class="rxui_input">
        <div>更新源:</div>
        <div class="rxui_input_content">
          <div class="ric_des">[必填] url:</div>
          <textarea type="text" name="i_url"
            class="div_input"
            id="rx_input_url" row="5"
            text="https://www.baidu.com"
            placeholder="请输入 api网址"
          ></textarea>
          <button id="btn_input_clear_url">清除</button>
        </div>
        <div class="rxui_input_content">
          <div class="ric_des">[可选] url密码:</div>
          <input type="text" name="i_password"
            class="div_input"
            id="rx_input_ps"
            placeholder="请输入 api网址 - 密码"
          >
          <button id="btn_input_clear_ps">清除</button>
        </div>
      </div>

      <div class="rxui_buttons rx_no_select">
        <button id="btn_cancel" class="rxui_button">取消</button>
        <button id="btn_update" class="rxui_button rxui_button_confim">检查更新</button>
      </div>

      <div class="des">
        <div>例如: 蓝奏云 分享链接</div>
        <span>
          https://lanzouyu.com/a/b/c  密码 1463
        </span>
      </div>

      <div class="des">
        <div>根据固定 api网址，进行文件检查</div>
        <span>
          1. 将最新文件下载到 `res/folder`<br>
          2. 解压后，删除原有的 `main.lua`<br>
          3. 删除下载文件<br>
          <br>
          文件更新信息: `res/update/update.txt`
        </span>
        <div></div>
      </div>
    </div>
  </div>


  <script>
    // 设置 配置 文件命
    var ShowUIConfig = 'RxUpdate_0_1.dat'
  </script>

  <script>
    // 请求工具
    function requestBase(method, ApiUrl, data, succ, fail, final, isTs) {
      isTs = isTs || false
      method = method || 'POST'
      data = data || ''

      let xhr = new XMLHttpRequest()

      if ("withCredentials" in xhr) {
        // XHR for Chrome/Firefox/Opera/Safari.
        xhr.open(method, ApiUrl, true);
      }
      else if (typeof XDomainRequest != "undefined") {
        // XDomainRequest for IE.
        xhr = new XDomainRequest();
        xhr.open(method, ApiUrl);
      }
      else {
        // CORS not supported.
        console.log('requestBase CORS not supported')
      }

      if (!xhr) {
        console.log('requestBase xhr=null')
        fail && fail('xhl error')
        final && final()
        return
      }

      xhr.setRequestHeader("Content-type", "application/json")
      xhr.onreadystatechange = function() {
        const XMLHttpReq = xhr
        if (XMLHttpReq.readyState == 4 && XMLHttpReq.status == 200) {
          const text = XMLHttpReq.responseText;
          console.log(text)
          succ && succ(text)
          final && final()
        }
      }
      xhr.send(data);
    }

    function requestGet(ApiUrl, data, succ, fail, final) {
      requestBase('GET', ApiUrl, data, succ, fail, final)
    }

    function requestPost(ApiUrl, data, succ, fail, final) {
      requestBase('POST', ApiUrl, data, succ, fail, final)
    }

    // ----- 按钮点击 确认
    function post_confirm(data) {
      console.log('点击 确认按钮 /set_event showUI_commit')
      requestPost(
        '/set_event', // postApi
        '{"name": "showUI_commit","value":' + data + '}', // data
        () => {
          // succ
        }, (msg) => {
          // false
          alert('确认 按钮点击\n' + msg)
        },
        null, // final
        true // isTs
      )
    }

    // ----- 按钮点击 取消
    function post_cancel() {
      console.log('点击 取消按钮 /set_event showUI_cancel')
      requestPost(
        '/set_event',
        '{"name": "showUI_cancel"}',
        () => {
          // succ
        }, (msg) => {
          // false
          alert('取消 按钮点击\n' + msg)
        },
        null, // final
        true // isTs
      )
    }

    // --- 获取 缓存
    function post_get_cache(cb) {
      console.log('获取 缓存=> /load_file')
      // alert('获取 缓存 ShowUIConfig=' + ShowUIConfig)
      requestPost(
        '/load_file',
        '{"name": "' + ShowUIConfig + '"}',
        (text) => {
          // succ
          cb && cb(text)
        }, (msg) => {
          // false
          // alert('获取缓存\n' + msg)
          cb && cb(false)
        },
        null, // final
        true // isTs
      )
    }

    // --- 保存 缓存
    function post_save_cache(data, cb) {
      console.log('保存 缓存=> /save_file')
      // alert('保存 缓存 ShowUIConfig=' + ShowUIConfig)
      requestPost(
        '/save_file',
        '{"name": "'+ ShowUIConfig + '", "data":' + data +'}',
        () => {
          // succ
          cb && cb(true)
        }, () => {
          // false
          alert('保存 缓存失败了\n' + msg)
          cb && cb(false)
        },
        null, // final
        true // isTs
      )
    }
  </script>

  <script>
    function getBtnInputUrl() {
      return document.getElementById('rx_input_url')
    }

    function getBtnInputPs() {
      return document.getElementById('rx_input_ps')
    }

    // 按钮点击
    function btnOnClick(btnId, cb) {
      document.getElementById(btnId).onclick = function() {
        cb && cb()
      }
    }

    // 点击取消
    btnOnClick('btn_cancel', () => post_cancel())

    // 点击确定
    btnOnClick('btn_update', () => {
      const input = getBtnInputUrl()
      const iv = input.value || ''
      const v = iv.trim() || ''

      const inputPs = getBtnInputPs().value || ''
      const ps = inputPs.trim() || ''

      if (!v) {
        alert('请输入正确的 api网址')
        return
      }

      if (v.indexOf('http') !== 0) {
        alert('请输入正确的 api网址')
        return
      }

      if (v.length < 11) {
        alert('请输入正确的 api网址')
        return
      }

      const vString = `{'url': '${v}', 'ps': '${ps}'}`
      console.log('确认按钮 vString=', vString)
      post_save_cache(vString, (isSave) => {
        // alert('保存缓存 isSave=' + isSave + '__' + vString)
        if (!isSave) {
          return
        }
        post_confirm(vString)
      })
    })

    btnOnClick('btn_input_clear_url', () => {
      const inputUrl = getBtnInputUrl()
      inputUrl.value = ''
    })

    btnOnClick('btn_input_clear_ps', () => {
      const inputPs = getBtnInputPs()
      inputPs.value = ''
    })
  </script>

  <script>
    function getCacheConfigFn() {
      console.log('获取缓存')
      post_get_cache((text)=> {
        // alert('获取 特定文件' + ShowUIConfig + '__是否存在')
        // alert('获取缓存 text=' + (typeof text) + '__'+ text + '__')
        // console.log('缓存 text=', text)

        /*
          {
            data: ___,
            success: true/false,
            message: ___
          }
         */
        if (text && typeof text === 'string') {
          let url = ''
          let ps = ''
          try {
            const t = JSON.parse(text) || {}
            const tdata = t.data || {}
            const succ = t.success || false
            const message = t.message || ''
            if (succ) {
              url = tdata.url || ''
              ps = tdata.ps || ''
            } else {
              alert(message)
            }
          } catch (error) {
            alert('error' + error.toString())
            url = ''
          }

          const inputUrl = getBtnInputUrl()
          inputUrl.value = url

          const inputPs = getBtnInputPs()
          inputPs.value = ps
        }
      })
    }
  </script>

</body>
</html>